// miniprogram/pages/study/study.js
const util = require('../../utils/util.js');
let md5 = require('../../utils/md5.js').md5
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    percent: 0,
    btnText: '下一题',
    rightNum: 0,
    idx: 0,
    length: 0,
    questions: [],
    question: {

    },
    errNum: 0,
    rightNum: 0,
    me: [],
    value: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options);
    let id = options.id;
  
    this.onQuery(id);
    this.onQueryItem(id);
    this.onGetOpenid();
    let ordernum = this.generate();
    this.setData({
      ordernum
    },()=>{
      console.log(this.data.ordernum);
    })
  },
  onQueryItem: function(id){
    const db = wx.cloud.database()
    db.collection('subject').doc(id)
    .get()
    .then(res=>{
      console.log('[数据库] [查询记录] 成功: ', res);
      app.globalData.subject = res.data;
    })
    .catch(err=>{
      console.error('[数据库] [查询记录] 失败：', err)
      wx.showToast({
        icon: 'none',
        title: '查询记录失败'
      })
    })
  },
  onQuery: function(id){
    // let items = ['2020020501','2020020502','2020020503','2020020504','2020020505','2020020506','2020020507','2020020508','2020020509','2020020510'];
    let that = this;
    const db = wx.cloud.database();

    db.collection('question')
    .where({
      subjectid: id
    })
    .get()
    .then(res => {
      console.log('[数据库] [查询记录] 成功: ', res)
      let questions = res.data;
      let items = [];
      questions.map((qu)=>{
        items.push(qu._id);
      })
      that.setData({
        items: items,
        md5: md5(items.join()),
        length: items.length
      },()=>{
        that.queryQues(items[that.data.idx]);
      })
      
    })

  },
  queryQues: function(id){
    let that = this;
    const db = wx.cloud.database();

    db.collection('question').doc(id)
    .get()
    .then(res => {
      console.log('[数据库] [查询记录] 成功: ', res)
      let question = res.data;
      let options = question.options;
      options.map((option)=>{
        option.selected = false;
      })
      that.setData({
        question,
        options
      })
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  generate: function(){
    return util.formatTime(new Date());
  },
  selectOption: function(e){
    console.log(e.currentTarget.dataset);
    let selectedOption = JSON.parse(e.currentTarget.dataset.value);
    let typecode = e.currentTarget.dataset.typecode;
    let options = this.data.options;
    switch(typecode){
      case '01':
          options.map((option)=>{
            option.selected = false;
            if(option.code == selectedOption.code){
              option.selected = true;
            }
          });
        break;
      case '02':
          options.map((option)=>{
            if(option.code == selectedOption.code){
              option.selected = !option.selected;
            }
          });
        break;
      case '03':
        options.map((option)=>{
          if(option.code == selectedOption.code){
            option.selected = !option.selected;
          }
        });
        break;
      case '04':
          console.log('填空题')
        break;  
      default: 
      console.log('其他未涉及题型')
    }
 

    this.setData({
      options
    })
  },
  bindKeyInput: function (e) {
    console.log(e.detail.value);
    this.setData({
      inputValue: e.detail.value
    })
  },
  bindBlurInput: function (e) {
    console.log(e.detail.value);
    let me = this.data.me;
    if(e.detail.value){
      me.push(e.detail.value);
    }
    
    console.log(me);
    this.setData({
      me,
      inputValue: e.detail.value
    })
  },
  goResult: function(){
      let url = '/pages/examresult/examresult?md5='+this.data.md5+'&length='+this.data.length+'&errNum='+this.data.errNum+'&rightNum='+this.data.rightNum+'&ordernum='+this.data.ordernum;
      wx.navigateTo({
        url: url
      })
  },
  generate: function(){
    return util.formatTime(new Date());
  },
  addNote: function(options){
    let that = this;
    let ordernum = this.data.ordernum;
    let question = this.data.question;
    question.options = options;
    const db = wx.cloud.database()
    db.collection('note').add({
      data: {
        ordernum: ordernum,
        question: this.data.question
      }
    })    
    .then(res=>{
      console.log('[数据库] [新增记录] 成功，记录 _id: ', res._id)
    })
    .catch(err=>{
      console.error('[数据库] [新增记录] 失败：', err)
      wx.showToast({
        icon: 'none',
        title: '新增记录失败'
      })
    })
  },
  addHistory: function(){
    let that = this;
    let time = util.getTime(new Date(Date.now()));
    let ordernum = this.data.ordernum;

    const db = wx.cloud.database()
    db.collection('history').add({
      data: {
        _id: ordernum,
        subject: app.globalData.subject,
        items: this.data.items,
        md5: this.data.md5,
        questions: this.data.questions,
        rightNum: this.data.rightNum,
        userInfo: app.globalData.userInfo,
        createTime: time
      }
    })
    .then(res=>{
      console.log('[数据库] [新增记录] 成功，记录 _id: ', res._id)
    })
    .catch(err=>{
      console.error('[数据库] [新增记录] 失败：', err)
      wx.showToast({
        icon: 'none',
        title: '新增记录失败'
      })
    })


  },
  onsetTimeOut: function(){
    setTimeout(()=>{
      this.doNext();
    },1000)
  },
  doNext: function(){
    console.log('doNext')
    
    
    
    let idx = this.data.idx;
    let length = this.data.length;
    idx++;

    let question = this.data.question;
    let options = this.data.options;
    let isRight = true;

    let me = this.data.me;
    
    let typecode = question.typecode;
    switch(typecode){
      case '01':


      case '02':
      case '03':
          for (const option of options) {
            console.log(option);
            if(option.selected == true && option.value == 0){
              isRight = false;
              break;
            }
          }
        break;
      case '04':
          console.log('填空题');
          // 先格式化数据
          for (const option of options) {
            if(me.indexOf(option.content) != -1){
              option.selected = true
            }
          }
          // 对格式化的数据进行判断
          isRight = false;
          for (const option of options) {
            console.log(option);
            // 只针对只有一个填空的情况
            if(option.selected == true && option.value == 1){
              isRight = true;
              break;
            }
          }
        break;  
      default: 
      console.log('其他未涉及题型')
    }
    console.log('答题情况')
    console.log(isRight);

    let rightNum = this.data.rightNum;
    let errNum = this.data.errNum;
    if(isRight){
      rightNum++;
    }else{
      errNum++;
      this.addNote(options);
    }

    let questions = this.data.questions;
    question.options = options;
    question.right = isRight;
    questions.push(question);

    let percent = (idx/length)*100;
    if(idx == length){
      this.setData({
        questions,
        rightNum,
        errNum
      },()=>{
        this.addHistory();
        this.goResult();
      })
      return;

    }

    if(length-idx == 1){
      this.setData({
        btnText: '完成'
      })
      wx.showToast({
        icon: 'none',
        title: '已经是最后一题了'
      })
    }

    let items = this.data.items;
    let id = items[idx];
    this.queryQues(id);

    this.setData({
      questions,
      value: '',
      rightNum,
      errNum,
      idx,
      percent
    },()=>{
      
    })
  },
  onGetOpenid: function() {
    let that = this;
    // 调用云函数
    wx.cloud.callFunction({
      name: 'login',
      data: {},
      success: res => {
        console.log('[云函数] [login]: ', res)
        that.setData({
          openid: res.result.openid
        })
        // wx.navigateTo({
        //   url: '../userConsole/userConsole',
        // })
      },
      fail: err => {
        console.error('[云函数] [login] 调用失败', err)
        wx.navigateTo({
          url: '../deployFunctions/deployFunctions',
        })
      }
    })
  }
})